<?php


class UserService extends Service
{
  /**
   * @param string $className
   * @return UserService
   */
  public static function instance($className = __CLASS__)
  {
    return parent::instance($className);
  }

  /**
   * 用户注册/编辑
   * @param array $data
   * @return array|bool
   */
  public function post($data = array())
  {
    if (empty($data['user_id'])) {
      $user = new User();
    } else {
      $user = User::model()->findByPk($data['user_id']);
    }
    $data['password'] = empty($data['password']) ? $user->password : md5($data['password']);
    $user->password = $data['password'];
    $user->attributes = $data;
    return $user->save() ? true : $user->errors;
  }

  /**
   * 设置用户状态
   * @param array $list
   * @param int $state
   * @return bool
   */
  public function setState($list = array(), $state = 0)
  {
    $criteria = new CDbCriteria();
    $criteria->addInCondition('user_id', $list);
    return User::model()->updateAll(array('state' => $state), $criteria) ? true : false;
  }

  /**
   * 获取用户列表
   * @param int $type 用户类型
   * @param int $pageSize 分页大小
   * @param string $keywords 搜索关键字
   * @return array
   */
  public function getList($type = 1, $pageSize = 20, $keywords = '')
  {
    $criteria = new CDbCriteria();
    $criteria->condition = 'type = :type';
    $criteria->params = array(':type' => $type);
    if (!empty($keywords)) {
      $criteria->addSearchCondition('name', $keywords);
    }
    $criteria->order = 'user_id desc';
    $count = User::model()->count($criteria);
    $pages = new CPagination($count);
    $pages->pageSize = $pageSize;
    $pages->applyLimit($criteria);
    $criteria->offset = $pages->currentPage * $pages->pageSize;
    $list = User::model()->findAll($criteria);
    return array(
        'list' => $list,
        'pages' => $pages
    );
  }

  /**
   * 修改密码
   * @param int $user_id
   * @param string $password
   * @return bool
   */
  public function changePassword($user_id = 0, $password = '')
  {
    $user = User::model()->findByPk($user_id);
    $user->password = md5($password);
    return $user->save()?true:false;
  }
} 